import axios from "axios";
import { validateCode, whiteList } from "./code/index";
import loadingTip from "@/components/bj-loading/loading";
import { getLoginData } from "@/tools";
let loadingInstance = null;
import router from "../router";
import { notificationTip } from "@/utils";
import { clearStorageData } from "@/tools";
let service = axios.create({
  timeout: 60000,
  withCredentials: false,
  //   baseURL:
  //     process.env.VUE_APP_CURRENTMODE == "development"
  //       ? process.env.VUE_APP_BASE_API
  //       : process.env.VUE_APP_TARGET,
  baseURL:
    process.env.VUE_APP_CURRENTMODE == "development"
      ? process.env.VUE_APP_BASE_API
      : window.location.origin + "/ltgateway",
  validateStatus: function (status) {
    return validateCode.includes(status);
  },
  headers: {
    "Content-Type": "application/json",
  },
});
//添加请求拦截器
service.interceptors.request.use(
  (config) => {
    let { customHeader, loading, isAuthorization } = config;

    let loginData = getLoginData();
    if (loading) {
      loadingInstance = loadingTip.service({
        lock: true,
        text: loading.text,
        background: "rgba(255, 255, 255, 0)",
      });
    }
    //统一添加请求头
    ["userId", "tenantCode", "sysSource", "token"].forEach((key) => {
      if (key == "token") {
        if (isAuthorization != false) {
          config.headers.Authorization = `Bearer ${loginData.token}`;
        }
      } else {
        config.headers[key] = encodeURIComponent(loginData[key]);
      }
    });

    //合并自定义请求头
    Object.assign(config.headers, customHeader || {});
    //构建完整的请求url
    // config.url = rebuildUrl(config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//添加相应拦截器
let authErroCode = [1401, 401];
service.interceptors.response.use(
  (response) => {
    let { data, status, config } = response;
    //关闭loading
    loadingInstance && loadingInstance.close();
    if (
      config.apiType == "file" &&
      status == 200 &&
      Object.prototype.toString.call(data) != "[object Object]"
    ) {
      return data;
    } else {
      if (data.code && whiteList.includes(parseInt(data.code))) {
        return data;
      } else if (validateCode.includes(status)) {
        let { code, msg, message } = data;
        if (authErroCode.includes(code)) {
          //跳转登录页
          clearStorageData();
          router.replace({
            path: "/login",
          });
        } else {
          notificationTip("error", msg || message || "未知错误");
        }
        return Promise.reject({
          code: parseInt(code),
          msg,
          data: {},
        });
      }
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default service;
